/*
Copyright 2019 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"bytes"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/gorilla/websocket"
	httpUtils "inspur.com/cloudware/util/http"
)

func main() {
	// DoPostTest()
	// DoGetTest()
	DoWsTest()
}

func DoPostTest() {
	client := httpUtils.NewHTTPClient()
	reqbody_str := "{\"age\":18,\"name\":\"Nicholas\"}"

	content := []byte(reqbody_str)
	req, err := httpUtils.BuildRequest(http.MethodPost, "http://127.0.0.1:3000/api/v1/ping", bytes.NewReader(content), "")
	if err != nil {
		fmt.Println(err.Error())
	}

	result, err := httpUtils.SendRequest(req, client)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(result)
}

func DoGetTest() {
	client := httpUtils.NewHTTPClient()

	req, err := httpUtils.BuildRequest(http.MethodGet, "http://127.0.0.1:3000/success", nil, "")
	if err != nil {
		fmt.Println(err.Error())
	}

	result, err := httpUtils.SendRequest(req, client)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(result)
}

func DoWsTest() {
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)
	c, _, err := websocket.DefaultDialer.Dial("ws://127.0.0.1:3000/ws/v1/connect", nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer c.Close()

	done := make(chan struct{})

	go func() {
		defer close(done)
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				return
			}
			log.Printf("recv: %s", message)
		}
	}()

	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-done:
			return
		case t := <-ticker.C:
			log.Println("write:", t.String())
			err := c.WriteMessage(websocket.TextMessage, []byte("我是client，现在时间是"+t.String()))
			if err != nil {
				log.Println("write:", err)
				return
			}
		case <-interrupt:
			log.Println("interrupt")

			// Cleanly close the connection by sending a close message and then
			// waiting (with timeout) for the server to close the connection.
			err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
			if err != nil {
				log.Println("write close:", err)
				return
			}
			select {
			case <-done:
			case <-time.After(time.Second):
			}
			return
		}
	}
}
